<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import ip from '@/utils/baseURL.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取当前用户的 session
const session = localStorage.getItem('session');

// 数据列表
const dataList = ref([])
const loading = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单数据
const formData = ref({
  id: '',
  type: '',
  content: '',
  remark: ''
})

// 表单规则
const rules = {
  type: [{ required: true, message: '请选择信息类型', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
}

// 类型选项
const typeOptions = [
  { label: '实验室简介', value: 'bri_info' },
  { label: '发展目标', value: 'goal' },
  { label: '联系方式', value: 'contact' },
  { label: '研究方向', value: 'direction' }
]

// 添加表单 ref
const formRef = ref(null)

// 获取数据列表
const fetchData = async () => {
  loading.value = true
  try {
    const response = await axios.get(`${ip}/inter/studio/getEssInfo`)
    if (response.data.code === 200) {
      dataList.value = response.data.data
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 打开编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  dialogTitle.value = '编辑信息'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 打开添加对话框
const handleAdd = () => {
  isEdit.value = false
  dialogTitle.value = '添加信息'
  formData.value = {
    id: '',
    type: '',
    content: '',
    remark: ''
  }
  dialogVisible.value = true
}

// 修改删除确认方法
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除这条信息吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`${ip}/inter/adminStudio/delete/${row.id}`,{
        headers: {
          'Session': `${session}`, // 传递 session
        },
      })
      ElMessage.success('删除成功')
      fetchData() // 刷新列表
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 修改提交表单方法
const submitForm = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        // 构造提交的数据
        const submitData = {
          type: formData.value.type,
          content: formData.value.content,
          remark: formData.value.remark
        }

        // 如果是编辑模式，添加 id
        if (isEdit.value) {
          submitData.id = formData.value.id
        }

        // 发送请求
        await axios.post(`${ip}/inter/adminStudio/saveOrUpdate`, submitData,{
          headers: {
            'Session': `${session}`, // 传递 session
          },
        })
        
        ElMessage.success(isEdit.value ? '更新成功' : '添加成功')
        dialogVisible.value = false
        fetchData() // 刷新列表
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <div class="about-page">
    <div class="header">
      <h2>实验室信息管理</h2>
      <el-button type="primary" @click="handleAdd">添加信息</el-button>
    </div>

    <!-- 数据列表 -->
    <el-table :data="dataList" style="width: 100%" v-loading="loading">
      <el-table-column label="类型" width="150">
        <template #default="{ row }">
          {{ typeOptions.find(item => item.value === row.type)?.label || row.type }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注" width="150" />
      <el-table-column prop="content" label="内容" show-overflow-tooltip />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="60%"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择信息类型">
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.about-page {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
    }
  }
}

:deep(.el-table) {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>